package com.t2t.top.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by yangpengfei on 2016/12/8.
 */
public class FileChannelTest {

    public static void main(String[] args) throws Exception {
        String path = FileChannelTest.class.getResource("/").getPath();

        RandomAccessFile aFile = new RandomAccessFile(path + "/data/nio-data.txt", "rw");
        FileChannel inChannel = aFile.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(48);

        int bytesRead = inChannel.read(buf);
        while (bytesRead != -1) {

            //System.out.println("Read " + bytesRead);
            buf.flip();//翻转这个缓冲区

            //每次48个字节进行
            while (buf.hasRemaining()) {
                System.out.print((char) buf.get());
            }

            buf.clear();
            bytesRead = inChannel.read(buf);
        }
        aFile.close();
    }

}
